/**
 * form插件，多用于新建，编辑页面
 */
class Form {
	/**
	 * @param {Object} options 
	 * @param {String} options.name form插件name
	 * @param {String} options.selector form元素的标识,标签，class，id等
	 * @param {String} options.url 提交的url,url也可以是动态的
 	 * @param {FUnction} options.success 提交成功的回调
	 */
	constructor(options = {}) {
		this.options = options;
		this.$form = $(this.options.selector);
	}

	/**
	 * form init
	 * @param {View} View 
	 */
	init(view) {
		let self = this;
		requirejs(['formValidation'], () => {
			requirejs(['frameworkBootstrap'], () => {
				this.validation = new Validation({
					selector: this.options.selector
				});
				this.formValidation = this.$form.formValidation($.po('formValidation', {
					button: {
						//selector: self.element,
						disabled: 'disabled'
					},
					fields: this.validation.init(this)
				})).data().formValidation;
				// this.$form.submit(function (e) {
				// 	e.preventDefault();
				// });
				this.$form.unbind('err.form.fv').bind('err.form.fv', function (e) {
					console.log(e)
				})
				this.$form.unbind('success.form.fv').bind('success.form.fv', function (e) {
					let data = $(e.target).serializeObject();
					//处理数组  以后优化
					for (let key in data) {
						if (key.indexOf('[]') > -1) {
							data[key.replace('[]', '')] = (data[key] instanceof Array) ? data[key] : [data[key]]
						}
					}
					//----------
					let url = '';
					if (self.options.type == 'edit' ||(view&& view.type === 'edit')) {
						url = self.options.edit_url || self.options.url;
					} else {
						url = self.options.add_url || self.options.url;
					}
					if (self.options.before_callback) {
						data = self.options.before_callback.call(self, data);
						if (data === false) {
							return false;
						}
					}
					if (self.options.loading) {
						$('#rotateCircle').css('display', 'block');
					}
					wdAjax.post({
						url: url,
						data: data,
						success: function (data) {
							if (self.options.success) {
								self.options.success.call(self, data);
								if (self.options.loading) {
									$('#rotateCircle').css('display', 'none');
								}
							} else {
								alertify.success('提交成功!')
							}
						},
						error: function (data) {
							let fv = self.$form.data('formValidation');
							fv.resetForm();
							if (self.options.error_callback) {
								self.options.error_callback.call(self, data);
							}
							if (self.options.loading) {
								$('#rotateCircle').css('display', 'none');
							}
						}
					})
					return false;
				});
				if (self.options.init_callback) {
					self.options.init_callback.call(self);
				}
			})
		})
		return false;
	}
	resetForm() {
		this.formValidation.resetForm()
	}

}
